import requests

class m3u8():
    def __init__(self,url):
        self.url = url

    def get_key_tsurl(self):
        """
        该函数会返回key和一个ts下载地址的列表
        :return: tsurl_list为ts文件的下载地址列表
        """
        second_url = ""
        all_content = requests.get(self.url).text  # 获取第一层M3U8文件内容
        if "#EXTM3U" not in all_content:
            raise BaseException("非M3U8的链接")

        if "EXT-X-STREAM-INF" in all_content:  # 第一层
            file_line = all_content.split("\n")
            for line in file_line:
                if '.m3u8' in line:
                    second_url = self.url.rsplit("/", 1)[0] + "/" + line  # 拼出第二层m3u8的URL
                    all_content = requests.get(second_url).text

        file_line = all_content.split("\n")

        unknow = True
        key = ""
        tsurl_list = []
        for index, line in enumerate(file_line):  # 第二层
            if "#EXT-X-KEY" in line:  # 找解密Key
                method_pos = line.find("METHOD")
                comma_pos = line.find(",")
                method = line[method_pos:comma_pos].split('=')[1]
                print("Decode Method：" + method)

                uri_pos = line.find("URI")
                quotation_mark_pos = line.rfind('"')
                key_path = line[uri_pos:quotation_mark_pos].split('"')[1]

                key_url = second_url.rsplit("/", 1)[0] + "/" + key_path  # 拼出key解密密钥URL
                res = requests.get(key_url)
                key = res.content


            if "EXTINF" in line:  # 找ts地址
                unknow = False
                pd_url = second_url.rsplit("/", 1)[0] + "/" + file_line[index + 1]  # 拼出ts片段的URL
                tsurl_list.append(pd_url)
                # print(pd_url)
        if unknow:
            raise BaseException("未找到对应的下载链接")
        else:
            if key == "":
                print("不需要key")
            else:
                print("key：" + key)
            print("ts列表获取成功")
        return key,tsurl_list
